<template>
  <view class="container">
    <view class="form">
      <uni-forms
        ref="form"
        :modelValue="form"
        label-position="right"
        label-width="80"
      >
        <uni-forms-item :label="`${$t('allocateact.form.name')}`">
          <uni-easyinput v-model="form.drugName" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${$t('allocateact.form.batchNumber')}`">
          <uni-easyinput v-model="form.batchNumber" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${getConfirmTime}`">
          <uni-easyinput v-model="form[getConfirmTimeVal]" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${getTotalNum}`">
          <UniNumberBox
            :value="form.totalNum"
            @change="numchange"
            :min="1"
            @foucs="formfocus"
            @blur="formblur"
            :focus="numFocus"
            :max="form.num"
          >
          </UniNumberBox>
        </uni-forms-item>
        <uni-forms-item :label="`${getNumText}`">
          <uni-easyinput v-model="form.num" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${getConfirmNumText}`">
          <uni-easyinput v-model="form.confirmNum" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${$t('allocateact.form.pendingNum')}`">
          <uni-easyinput v-model="form.pendingNum" disabled />
        </uni-forms-item>
        <uni-forms-item :label="`${$t('allocateact.form.warehouse')}`">
          <view>
            <uni-easyinput v-model="form.warehouseName" disabled="" />
          </view>
        </uni-forms-item>
        <uni-forms-item :label="`${$t('allocateact.form.shelfName')}`">
          <view>
            <uni-easyinput v-model="form.shelfName" disabled="" />
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="bottom-btn">
      <button class="button" type="primary" @click="allocateBatch">
        {{ $t('allocateact.form.btn') }}
      </button>
    </view>
    <view>
      <keyboard-listener @keydown="scancodelisten"></keyboard-listener>
    </view>
  </view>
</template>

<script>
import api from '../../common/api.js';
import common from '../../common/common.js';
import UniNumberBox from '@/components/uni-number-box/uni-number-box.vue';
import KeyboardListener from 'uniapp-keyboard-listener';

export default {
  components: {
    UniNumberBox,
    KeyboardListener
  },
  data() {
    return {
      timer: null,
      id: '',
      isFocus: true,
      numFocus: false,
      pdacode: '',
      form: {},
      code: '',
      changeInput: false,
      // tab
      tabCurrent: ''
    };
  },
  computed: {
    // 请求函数
    pageFunc() {
      return this.tabCurrent === 'in'
        ? api.getAllocateInboundDetailPage
        : api.getAllocateOutboundDetailPage;
    },
    // 查询参数
    pageOrderId() {
      return this.tabCurrent === 'in' ? 'inboundOrderId' : 'outboundOrderId';
    },
    // 数量
    getNumText() {
      return this.tabCurrent === 'in'
        ? this.$t('allocateact.form.inboundNum')
        : this.$t('allocateact.form.outboundNum');
    },
    getConfirmNumText() {
      return this.tabCurrent === 'in'
        ? this.$t('allocateact.form.inboundConfirmNum')
        : this.$t('allocateact.form.outboundConfirmNum');
    },
    getTotalNum() {
      return this.tabCurrent === 'in'
        ? this.$t('allocateact.form.inboundTotalNum')
        : this.$t('allocateact.form.outboundTotalNum');
    },
    // 时间
    getConfirmTime() {
      return this.tabCurrent === 'in'
        ? this.$t('allocateact.form.confirmInboundTime')
        : this.$t('allocateact.form.confirmOutboundTime');
    },
    getConfirmTimeVal() {
      return this.tabCurrent === 'in'
        ? 'confirmInboundTime'
        : 'confirmOutboundTime';
    },
    // 手动调拨接口
    allocateBatchFunc() {
      return this.tabCurrent === 'in'
        ? api.putAllocateInboundDetail
        : api.putAllocateOutboundDetail;
    },
    allocateBatchId() {
      return this.tabCurrent === 'in'
        ? 'inboundOrderDetailId'
        : 'outboundOrderDetailId';
    }
  },
  onNavigationBarButtonTap(e) {
    console.log(e, '----e---');
    this.code = '';
    let that = this;
    uni.scanCode({
      success: async function (res) {
        console.log('条码类型：' + res.scanType);
        console.log('条码内容：' + res.result);
        that.code = res.result;
        await that.sendCode();
      }
    });
  },
  async onLoad(option) {
    console.log('上一个页面传递过来的参数', option);
    this.form.id = option.id;
    this.tabCurrent = option.tabCurrent;
    if (this.form.id !== undefined) {
      await this.findbyId();
      this.isFocus = true;
      // this.timer = setInterval(() => { uni.hideKeyboard(); }, 500)
    } else {
      uni.navigateBack();
    }
  },
  async onUnload() {
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    async scancodelisten(e) {
      let keyCode = e.keyCode;
      // console.log(e, '-----e---')
      if (
        (keyCode >= 65 && keyCode <= 90) ||
        (keyCode >= 97 && keyCode <= 122)
      ) {
        console.log('字母输入:', e.key);
        this.pdacode = this.pdacode + e.key;
      } else if (keyCode >= 48 && keyCode <= 57) {
        console.log('数字输入:', e.key);
        console.log(this.numFocus, 'numFocus');
        this.pdacode = this.pdacode + e.key;
      } else if (keyCode === 13) {
        this.code = this.pdacode;
        if (this.code !== '') {
          await this.sendCode();
        }
        this.pdacode = '';
      } else {
        console.log('其他输入:', e.key);
      }

      console.log(this.pdacode, '-----this.pdacode---');
    },
    numchange(e) {
      this.form.totalNum = Number(e);
    },
    async findbyId() {
      uni.showLoading();
      let ret = await this.pageFunc({
        id: this.form.id,
        page: { pageNumber: 1, pageSize: 50 }
      });
      console.log(ret, '------ret');
      if (ret.code === 0 && ret.data) {
        const {
          id,
          drugName,
          batchNumber,
          warehouseName,
          shelfName,
          num,
          confirmNum,
          pendingNum,
          confirmInboundTime,
          confirmOutboundTime
        } = ret.data.items[0];
        this.form = {
          ...ret.data.items[0],
          // 填写数量
          totalNum: 0,
          confirmInboundTime: confirmInboundTime
            ? common.formatDate(confirmInboundTime)
            : '-',
          confirmOutboundTime: confirmOutboundTime
            ? common.formatDate(confirmOutboundTime)
            : '-'
        };
        uni.hideLoading();
      } else {
        uni.showToast({
          title: ret.message,
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      }
    },
    formfocus(e) {
      this.pdacode = '';
      setTimeout(() => {
        this.isFocus = false;
        this.numFocus = true;
      }, 0);
    },
    formblur(e) {
      console.log(e.detail.value);
      this.pdacode = '';
      this.numFocus = false;
    },
    input(e) {
      console.log('键盘输入:' + e.detail.value);
      this.isFocus = false;
    },
    focus() {
      console.log('输入框聚焦');
    },
    blur() {
      console.log('输入框失去焦点');
      // this.isFocus = true;
    },
    async confirm(e) {
      console.log('点击完成按钮');
      await this.sendCode();
    },
    chooseWarehouse() {
      uni.hideKeyboard();
      console.log('chooseWarehouse');
    },
    close() {
      console.log('close');
    },
    // 手动调拨按钮
    async allocateBatch() {
      uni.showLoading();
      const params = Object.assign({
        [this.allocateBatchId]: this.form.id,
        totalNum: this.form.totalNum
      });
      let ret = await this.allocateBatchFunc(params);
      if (ret.code === 0 && ret.success) {
        uni.hideLoading();
        uni.navigateBack();
      } else {
        uni.hideLoading();
        this.$nextTick(() => {
          uni.showToast({
            title: ret.msg,
            icon: 'none'
          });
        });
      }
    },
    async sendCode() {
      uni.showLoading();
      let ret = await this.pageFunc({
        id: this.code
      });
      if (ret.code === 0 && ret.data) {
        let checkName = ret.data.drugName === this.form.name;
        let checkWarehouseName = ret.data.warehouseName === this.form.warehouse;
        let checkshelfName = ret.data.shelfName === this.form.shelfName;
        let checkOutboundOrderId = ret.data.id === this.form.id;
        if (
          checkName &&
          checkWarehouseName &&
          checkshelfName &&
          checkOutboundOrderId
        ) {
          this.form.totalNum++;
          uni.hideLoading();
        } else {
          uni.hideLoading();
          this.$nextTick(() => {
            uni.showToast({
              title: this.$t('scan.dataerror'),
              icon: 'none'
            });
          });
        }
      } else {
        uni.hideLoading();
        this.$nextTick(() => {
          uni.showToast({
            title: ret.message,
            icon: 'none'
          });
        });
      }
    }
  }
};
</script>

<style>
.form {
  margin-bottom: 40rpx;
}

.bottom-btn {
  position: absolute;
  width: 100%;
  bottom: 0;
}

.code-item {
  display: flex;
  flex: 1;
}
</style>
